class Article < ActiveRecord::Base

  scope :published, -> { where.not(published_at: nil) }
  scope :for_index, -> { includes(:preview, :category).published.where.not(slug: nil).order(published_at: :desc) }
  scope :archives,  -> { published.where.not(slug: nil).order(published_at: :desc) }

  validates :title, presence: true

  has_one :preview, class_name: 'ArticlePreview', foreign_key: :article_id, dependent: :destroy, autosave: true
  has_one :content, class_name: 'ArticleContent', foreign_key: :article_id, dependent: :destroy, autosave: true

  belongs_to :user, foreign_key: :user_id
  belongs_to :category, foreign_key: :category_id

  attr_accessor :keep_slug

  def content_field
    content.try :body
  end

  def content_field=(content_text)
    doc = Nokogiri::HTML(content_text)
    doc.css('h1')[0].remove
    #html = doc.css('body').inner_html
    content = self.content ||= build_content
    preview = self.preview ||= build_preview
    content.doc = doc
    preview.doc = doc
  end

  before_save :reset_slug
  def reset_slug
    self.slug = nil if title_changed? and not keep_slug
  end

  after_save :translate_title_when_change
  def translate_title_when_change
    delay.translate_title if title_changed? and not keep_slug
  end

  def translate_title
    text_translator = Termit::TextTranslator.new source_lang: 'zh', target_lang: 'en', text: title.gsub(/\p{P}/, ' ')
    slug = text_translator.call
    update slug: slug.gsub(/('s\s|\p{P})/u, ' ').gsub(/\s+/, '-').downcase
  end

  after_save :recount_category_on_save
  def recount_category_on_save
    if category_id_changed? or published_at_changed?
      Category.recount category_id, category_id_was
    end
  end

  after_destroy :recount_category_on_destroy
  def recount_category_on_destroy
    Category.recount category_id
  end
end
